package shotgun.my.sweetutil.mytest;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MusicRepeatUtil {

    public static void main(String[] args) {
        //扫描目录
        String dirPath = "D:\\appData\\qqmusic";
        //扫描文件类型
        List<String> scanTypes = Stream.of("ogg", "mp3", "flac", "mflac", "qmcflac", "mgg").collect(Collectors.toList());


        //优先重复的vip歌曲（ "mflac", "qmcflac","mgg" 为qq音乐vip歌曲）
        List<String> firstDeleteFileType = Stream.of("mflac", "qmcflac", "mgg").collect(Collectors.toList());

        File dir = new File(dirPath);

        File[] files = dir.listFiles();

        int[] count = {0};
        if (files != null && files.length > 0) {

            Map<String, List<File>> groupFileMap = Arrays.stream(files).filter(file -> scanTypes.contains(getFileType(file.getName()))).collect(Collectors.groupingBy(file -> {

                int lastIndex = file.getName().lastIndexOf(".");
                return file.getName().substring(0, lastIndex >= 0 ? lastIndex : file.getName().length() - 1);
            }));

            groupFileMap.forEach((s, filesColl) -> {
                if (filesColl.size() > 1) {
                    //优先删除的类型先查找
                    Optional<File> min = filesColl.stream().filter(file -> firstDeleteFileType.contains(getFileType(file.getName()))).findAny();

                    if (!min.isPresent()) {
                        //同名文件，移除文件较小的
                        min = filesColl.stream().min((o1, o2) -> {
                            long l = o1.length() - o2.length();
                            return l > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) l;
                        });
                    }

                    System.out.println(filesColl);
                    min.ifPresent(file -> {
                        System.out.println(file.getAbsolutePath() + ":::(delete)");
                        file.delete();
                        count[0]++;
                    });


                }
            });

        }

        System.out.println("移除重复文件数量：" + count[0]);

        System.out.println("执行完毕 end...");
    }


    public static String getFileType(String fileName) {
        int i = fileName.lastIndexOf(".");
        return i > -1 ? fileName.substring(i + 1) : fileName;
    }

    public static String getFileNameExcludeType(String fileName) {
        int i = fileName.lastIndexOf(".");
        return i > -1 ? fileName.substring(0, i) : fileName;
    }


}
